package com.qcxk.yuqian.system.component.token.front;

import com.alibaba.fastjson.JSONObject;
import com.qcxk.yuqian.system.component.constant.SystemConstant;
import com.qcxk.yuqian.system.utils.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Component
public class FrontTokenProccessor {
    @Autowired
    private RedisUtil redisUtil;
    @Value("${login.outtime}")
    private Long SYS_LOGIN_TOKEN_OUTTIME;
    @Value("${login.only}")
    public boolean SYS_LOGIN_ONLY;

    /**
     * 生成Token Token：Nv6RRuGEVvmGjB+jimI/gw==
     *
     * @return
     */
    public String makeToken() { // checkException
        String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
        // 数据指纹 128位长 16个字节 md5
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte md5[] = md.digest(token.getBytes());
            // base64编码--任意二进制编码明文字符
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(md5);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject verifyToken(HttpServletRequest request, String token) {
        JSONObject json = new JSONObject();
        //读取redis校验token
        if (StringUtils.isNotBlank(token) && redisUtil.hasKey(token)) {
            //刷新有效期
            if (SYS_LOGIN_ONLY) {
                String id = (String) redisUtil.get(token);
                String newtoken = (String) redisUtil.get(id);
                if (newtoken.equals(token)) {
                    redisUtil.expire(id, SYS_LOGIN_TOKEN_OUTTIME);
                    json.put("code", "0");
                    json.put("msg", SystemConstant.SYS_TOKEND_VALIDATE_SUCCESS_CN);
                } else {
                    redisUtil.del(token);
                    json.put("code", "2");
                    json.put("msg", SystemConstant.SYS_TOKEND_VALIDATE_ERROR1_CN);
                }
            } else {
                redisUtil.expire(token, SYS_LOGIN_TOKEN_OUTTIME);
                json.put("code", "0");
                json.put("msg", SystemConstant.SYS_TOKEND_VALIDATE_SUCCESS_CN);
            }

        } else {
            json.put("code", "2");
            json.put("msg", SystemConstant.SYS_LOGIN_TIMEOUT_CN + "");
        }
        return json;
    }
}
